package com.yonyou.trumpchi;

import android.app.Activity;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.yonyou.trumpchi.entity.ServiceInfo;
import com.yonyou.trumpchi.model.ServiceModel;

import java.util.HashMap;

/**
 * @author liuxiaopeng
 * @version V1.0.0
 * @time 2016/11/24
 * @describe WebView提供JS方法
 */

public class JavaScriptInterface {
    public Activity mContext;
    public ServiceInfo info;
    public Gson gson;
    public WebView webView;

    public JavaScriptInterface(Activity context, ServiceInfo info, WebView webView) {
        this.mContext = context;
        this.info = info;
        this.webView = webView;
        gson = new Gson();
    }

    /**
     * 获取
     *
     * @param key key值
     * @return value值
     */
    @JavascriptInterface
    public String get(String key) {
        String value = info.getParams().get(key);
        if (TextUtils.isEmpty(value)) {
            value = "";
        }
        return value;
    }

    /**
     * 保存
     *
     * @param key   key值
     * @param value value值
     */
    @JavascriptInterface
    public void put(String key, String value) {
        if (Constants.SP_AUTO.equals(key) && "1".equals(value)) {//将其他服务器设置为0 （及其他服务器不自动登录）
            ServiceModel.setOtherAuto(mContext, info.getUrl());
        }
        info.getParams().put(key, value);
        SPUtils.put(mContext, info.getUrl(), gson.toJson(info));
    }

    /**
     * 切换服务器
     */
    @JavascriptInterface
    public void upDataService() {
        this.put(Constants.SP_AUTO, "0");
        this.put(Constants.SP_PASSWORD, "");
        this.put(Constants.SP_USERNAME, "");
        webView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(MainActivity.HOME_URL);
                webView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        webView.clearHistory();
                    }
                }, 1000);
            }
        });
//        handler.sendEmptyMessage(1);
    }

    /**
     * 注销
     */
    @JavascriptInterface
    public void exit() {
        info.setParams(new HashMap<String, String>());
        SPUtils.put(mContext, info.getUrl(), gson.toJson(info));
        mContext.finish();
    }
}
